package com.gopay.bis.ipay.expay.operation;

import java.security.KeyFactory;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.Signature;
import java.security.spec.PKCS8EncodedKeySpec;

import org.apache.commons.codec.binary.Base64;
import org.apache.commons.lang.builder.ToStringBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;

import com.gopay.bis.common.util.BankLogUtils;
import com.gopay.bis.ipay.ebank.rsa.CryptoUtil;
import com.gopay.common.constants.proccode.ProcCodeConstants;
import com.gopay.common.domain.bank.BaseMessage;
import com.gopay.common.domain.bank.ipay.ebank.IpayMessage;
import com.gopay.common.domain.bank.ipay.expay.IpayExPayBaseMessage;
import com.gopay.common.domain.bank.ipay.expay.PayResultNotify;
import com.gopay.common.exception.GopayException;
import com.gopay.remote.bank.ICertHelper;

import net.sf.json.JSONObject;

/**
 * @IpayExpayCerHelper.java
 * @author jiangxiangjiao
 */
@SuppressWarnings("all")
public class IpayExpayCerHelper implements ICertHelper {

	private static Logger logger = LoggerFactory.getLogger(IpayExpayCerHelper.class);

	@Override
	public String sign(BaseMessage baseMsg) throws GopayException {
		IpayExPayBaseMessage message = (IpayExPayBaseMessage) baseMsg;
		// 签名
		try {
			PrivateKey hzfPriKey = CryptoUtil.getRSAPrivateKeyByFileSuffix(baseMsg.getPrivateKeyPath(), "pem", null, "RSA");
			byte[] base64SingDataBytes = Base64.encodeBase64(
					CryptoUtil.digitalSign(message.getPlainMessage().getBytes("UTF-8"), hzfPriKey, "SHA1WithRSA"));
			return new String(base64SingDataBytes, "UTF-8");
		} catch (Exception e) {
			BankLogUtils.printExPaySignExceptionLog(message, e);
			throw new GopayException(ProcCodeConstants.PROC_CODE_100E6057);
		}
	}
	
	@Override
	public Object verify(BaseMessage baseMsg) throws GopayException {
		IpayExPayBaseMessage message = (IpayExPayBaseMessage) baseMsg;
		boolean verifySign = false;
		try {
			PublicKey hzfPubKey = CryptoUtil.getRSAPublicKeyByFileSuffix(baseMsg.getPublicKeyPath(), "pem", "RSA");
			byte[] signBytes = Base64.decodeBase64(message.getSignMessage().getBytes("UTF-8"));
			// 使用商户公钥验证签名
			verifySign = CryptoUtil.verifyDigitalSign(message.getPlainMessage().getBytes("UTF-8"), signBytes, hzfPubKey,
					"SHA1WithRSA");
		} catch (Exception e) {
			BankLogUtils.printExPaySignExceptionLog(message, e);
			throw new GopayException(ProcCodeConstants.PROC_CODE_100E6057);
		}
		return verifySign;
	}

}
